﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Marmat.Template.WinForm;

namespace 测试项目.NewFolder1
{
    class RelationProvider<Entity>
    {
        private readonly Dictionary<string, System.Collections.IEnumerable> dic = new Dictionary<string, System.Collections.IEnumerable>();

        public void Load<T>(IEnumerable<Entity> data, string propertyName, IAdvRelationProvider<T> provider)
        {
            if (data is null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            List<object> list = new List<object>();
            var member = typeof(Entity).GetMembers().Where(x => x.Name == propertyName && (x is FieldInfo || x is PropertyInfo)).First();
            if (member is FieldInfo field)
            {
                foreach (var item in data)
                {
                    var value = field.GetValue(item);
                    list.Add(value);
                }
            }
            else if (member is PropertyInfo property)
            {
                foreach (var item in data)
                {
                    var value = property.GetValue(item);
                    list.Add(value);
                }
            }
            list = list.Where(x => x is not null && !string.IsNullOrEmpty(x.ToString())).Distinct().ToList();
            var dataSource = provider.Load(list);
            dic[propertyName] = dataSource;
        }

        public T GetObject<T>(Entity item, string propertyName, Func<T, bool> func)
        {
            var dataSource = dic[propertyName];
            object propertyValue = null;
            var member = typeof(Entity).GetMembers().Where(x => x.Name == propertyName && (x is FieldInfo || x is PropertyInfo)).First();
            if (member is FieldInfo field)
                propertyValue = field.GetValue(item);
            else if (member is PropertyInfo property)
                propertyValue = property.GetValue(item);
            foreach (var obj in dataSource)
            {
                if (obj is T tmp)
                {
                    if (func(tmp))
                    {
                        return tmp;
                    }
                }
            }
            return default;
        }
    }
}
